package com.wjw.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wjw.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证token合法性的：拦截器
 * 该拦截器需在InterceptorConfig中进行配置
 */
public class JWTInterceptor implements HandlerInterceptor{

    /**
     * 拦截所有请求,获取请求头中的token,并对token进行验证
     * 如果token合法,放行该请求
     * 如果token不合法,拦截该请求,并返回错误信息给前台
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();
        //一般token都放在请求头中,获取请求头中的token值
        String token = request.getHeader("token");
        try {
            //验证token的合法性
            JwtUtils.verifyToken(token);
            return true;//放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg","无效签名！！");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg","token已过期！！");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg","token算法不一致！！");
        }catch (Exception e) {
            e.printStackTrace();
            map.put("msg","token无效！！");
        }
        //将map手动转为json,返回给前台,提示错误信息
        map.put("state",false);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;//拦截请求
    }
}
